package com.hzncc.flowable_diboot.contract.controller;

import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.util.S;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.annotation.OperationCons;
import com.hzncc.flowable_diboot.constans.PermissionCons;
import com.hzncc.flowable_diboot.contract.dto.SalesContractDTO;
import com.hzncc.flowable_diboot.contract.entity.SalesContract;
import com.hzncc.flowable_diboot.contract.entity.SalesContractExt;
import com.hzncc.flowable_diboot.contract.entity.SalesContractMrl;
import com.hzncc.flowable_diboot.contract.service.*;
import com.hzncc.flowable_diboot.contract.vo.SalesContractDetailVO;
import com.hzncc.flowable_diboot.contract.vo.SalesContractListVO;
import com.hzncc.flowable_diboot.vo.refundmanage.RefundCertDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 销售合同 相关rest接口
 *
 * @author MyName
 * @version 1.0
 * @date 2024-09-02
 * Copyright © MyCorp
 */
@Slf4j
@RequestMapping("/sales-contract")
@BindPermission(name = "销售合同")
@RestController
public class SalesContractController extends BaseCrudRestController<SalesContract> {

    @Autowired
    private SalesContractService salesContractService;

    @Autowired
    private SalesContractExtService salesContractExtService;

    @Autowired
    private SalesContractMrlService salesContractMrlService;

    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/delivery-status/{contractCode}")
    public JsonResult<?> getDeliveryStatus(@PathVariable("contractCode") String contractCode) throws Exception {
        String deliveryStatus = salesContractService.getDeliveryStatusByContractCode(contractCode);
        return JsonResult.OK(deliveryStatus);
    }

    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/invoice-status/{contractCode}")
    public JsonResult<?> getInvoiceStatus(@PathVariable("contractCode") String contractCode) throws Exception {
        String invoiceStatus = salesContractService.getInvoiceStatusByContractCode(contractCode);
        return JsonResult.OK(invoiceStatus);
    }

    /**
     * 查询资源对象的列表VO记录
     * <p>
     * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<SalesContractListVO>> getListVOMapping(SalesContractDTO queryDto, Pagination pagination) throws Exception {
        return super.getViewObjectList(queryDto, pagination, SalesContractListVO.class);
    }

    /**
     * 根据指定字段和值查询资源对象的详情VO
     *
     * @param fieldName  字段名
     * @param fieldValue 字段值
     * @return
     * @throws Exception
     */
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{fieldName}/{fieldValue}")
    public JsonResult<SalesContractDetailVO> getDetailVOMapping(@PathVariable("fieldName") String fieldName, @PathVariable("fieldValue") String fieldValue) throws Exception {
        SalesContractDetailVO detailVO = salesContractService.getViewObject(fieldName, fieldValue, SalesContractDetailVO.class);
        return JsonResult.OK(detailVO);
    }

    /**
     * 根据id查询资源对象的详情VO
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<SalesContractListVO> getDetailVOMapping(@PathVariable("id") String id) throws Exception {
        SalesContractListVO detailVO = salesContractService.getViewObject(id, SalesContractListVO.class);
        List<SalesContractMrl> mrlList = detailVO.getMrlList();
        salesContractService.checkMrlCanPush(mrlList, detailVO.getSalesOrganization(), detailVO.getDistributionChannel());
        return JsonResult.OK(detailVO);
    }


    /**
     * 创建资源对象数据
     *
     * @param salesContract
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<?> createModelMapping(@RequestBody SalesContractListVO salesContract) throws Exception {
        boolean success = salesContractService.createEntity(salesContract);
        SalesContractExt ext = salesContract.getExt();
        if (ext != null) {
            ext.setSalesContractId(salesContract.getId());
        }
        List<SalesContractMrl> mrlList = salesContract.getMrlList();
        if (mrlList != null && mrlList.size() > 0) {
            mrlList.forEach(e -> e.setSalesContractId(salesContract.getId()));
        }
        salesContractExtService.createEntity(ext);
        salesContractMrlService.createEntities(mrlList);
        log.debug("新建数据 销售合同:{} {}", salesContract.getId(), success ? "成功" : "失败");
        return JsonResult.OK(salesContract.getId());
    }

    /**
     * 批量创建资源对象数据
     *
     * @param salesContractList
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch")
    public JsonResult<?> batchCreateModelMapping(@RequestBody List<SalesContract> salesContractList) throws Exception {
        boolean success = salesContractService.createEntities(salesContractList);
        log.debug("批量新建数据 销售合同 {}", success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id更新资源对象
     *
     * @param salesContract
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id") String id, @RequestBody SalesContract salesContract) throws Exception {
        boolean success = salesContractService.updateEntity(salesContract);
        log.debug("更新数据 销售合同:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = salesContractService.deleteEntity(id);
        log.debug("删除数据 销售合同:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据ids集合删除资源对象
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = salesContractService.deleteEntities(ids);
        log.debug("批量删除数据 销售合同:{} {}", ids, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 取消合同
     *
     * @param id
     * @return
     * @throws Exception
     * @author 陈广煜
     * @date 2024-09-14
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/cancel/{id}")
    public JsonResult<?> cancel(@PathVariable("id") String id) throws Exception {
        salesContractService.cancelSap(id);
        return JsonResult.OK();
    }

    /**
     * 保存并推送
     *
     * @param salesContract
     * @return
     * @throws Exception
     * @author 陈广煜
     * @date 2024-09-14
     */
    @Log(operation = PermissionCons.SAP_PUSH_LABEL)
    @BindPermission(name = PermissionCons.SAP_PUSH_LABEL, code = PermissionCons.SAP_PUSH)
    @PostMapping("/save-and-push")
    public JsonResult<?> saveAndPush(@RequestBody SalesContractListVO salesContract) throws Exception {
        salesContractService.pushSap(salesContract);
        return JsonResult.OK();
    }

    /**
     * 根据合同项目ID获取销售合同
     *
     * @param id
     * @return
     * @author 陈广煜
     * @date 2024-09-14
     */
    @Log(operation = PermissionCons.SAP_PUSH_LABEL)
    @BindPermission(name = PermissionCons.SAP_PUSH_LABEL, code = PermissionCons.SAP_PUSH)
    @PostMapping("/create/{id}")
    public JsonResult<SalesContractListVO> getSalesContract(@PathVariable String id, String type) {
        if (S.equals(type, "project")) {
            return JsonResult.OK(salesContractService.getSalesContractFormProject(id));
        }
        SalesContractListVO salesContract = salesContractService.getSalesContract(id);
        return JsonResult.OK(salesContract);
    }

    /**
     * 检查是否全推送
     *
     * @param id
     * @return true 全推送 false 未推送
     * @throws Exception
     * @author 陈广煜
     * @date 2024-09-14
     */
    @GetMapping("/check-full-push/{id}")
    public JsonResult<?> checkSap(@PathVariable String id) throws Exception {
        return JsonResult.OK(salesContractService.checkSap(id));
    }

    /**
     * 批量推送
     * @param ids 合同项目id
     * @return
     * @throws Exception
     */
    @PostMapping("/batch-push")
    public JsonResult<?> batchPushSap(@RequestBody List<String> ids) throws Exception {
        salesContractService.batchPushSap(ids);
        return JsonResult.OK();
    }

}